define([
    'base',
    'bootstrapDialog',
    'bootstrapTable',
    'plugins/ztree/ztree'
], function (base,BootstrapDialog) {
    //默认加载基础库
    base();

    return {
        list: function () {
            var myTable = $('#adminUserList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'api.json'})
            };


            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    winModal("编辑", row, 1);
                },
                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        nameText: '账号',
                        nameValue: row.userName,
                        url: '../status/action'
                    });
                },
                'click .change': function (e, value, row) {
                    winModal("修改密码", row, 2);
                }
            };
            //table表格
            myTable.bootstrapTable({
                url: 'api.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [{ // 列设置
                    field: 'state',
                    checkbox: true // 使用复选框
                }, {
                    field: 'id',
                    title: '编号'
                }, {
                    field: 'userName',
                    title: '账号',
                    formatter: function (value, row) {
                        if (row.ukey !== null && row.ukey !== '') {
                            return value+"&emsp;<span class=\"text text-danger\">(UKEY)</span>";
                        } else {
                            return value;
                        }
                    }
                }, {
                    field: 'nickName',
                    title: '昵称'
                }, {
                    field: 'roleName',
                    title: '角色'
                }, {
                    field: 'loginIp',
                    title: '登陆IP'
                }, {
                    field: 'loginTime',
                    title: '登陆时间'
                }, {
                    field: 'updateName',
                    title: '更新人'
                }, {
                    field: 'updateTime',
                    title: '更新时间'
                }, {
                    field: 'status',
                    title: '状态',
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (value == 1) {
                            return '<span class="label label-primary">正常</span>';
                        } else {
                            return '<span class="label label-danger">已禁</span>';
                        }
                    }
                }, {
                    field: 'action',
                    title: '操作',
                    align: 'center',
                    formatter: operateFormatter,
                    events: operateEvents
                }
                ]
            });

            //搜索刷新
            $('#search').on('click', function () {
                tableRefresh();
            });

            //toolbar按钮相应事件
            //新增
            $(".toolbar-save").on('click', function () {
                winModal("新增", null, 1);
            });
            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });
            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.userName);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '账号',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择最少一条记录后再操作", "信息提示");
                }

            });


            //搜索参数传递
            function queryParams(params) {
                params.search = $(".searchValue").val().trim();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    search: params.search
                };
            };

            //回显
            function responseHandler(res) {
                return res.rows;
            };

            //模态框
            //type:1新增&编辑，2改密
            function winModal(title, row, type) {
                var htmlUrl, postUrl;
                if (type == 1) {
                    htmlUrl = "../save/form.html";
                    postUrl = "../save/action";
                } else if (type == 2) {
                    htmlUrl = "../password/form.html";
                    postUrl = "../password/action";
                }
                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    title: title,
                    closable: true,	//关闭箭头启动
                    closeByBackdrop: false,	//点击空白不消失
                    closeByKeyboard: true,//ESC取消禁用
                    message: $('<div></div>').load(htmlUrl),
                    data: {
                        'row': row,
                    },
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: '提交' + title,
                        //hotkey: 13,//回车提交
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            //返回验证结果
                            var flag = $("#winModal").validate().form();
                            if (flag) {
                                $.baseUtils.ajax({
                                    dialog: dialog,
                                    url: postUrl,
                                    data: $("#winModal").serialize(),
                                    text: "保存",
                                    isTable: true,
                                    tableName: '#adminUserList',
                                    isDialog: true
                                })
                            }
                        }
                    }],
                    onshown: function (dialog) {

                        //角色下拉插件
                        var roleSelect = $.baseUtils.select({
                            cssName: "#roleId",
                            dataName: "roleName",
                            url: "../../adminRole/view/roleSelect.json"
                        });

                        // //组织架构下拉插件
                        // $.baseUtils.select({
                        //     cssName: "#orgParentId",
                        //     dataName: "orgName",
                        //     url: "../../adminOrg/view/orgSelect.json",
                        //     minimumResultsForSearch: 0,
                        //     templateResult: templateResult
                        // });

                        // //重写组织架构列表模板
                        // function templateResult(repo) {
                        //     if (repo.loading) return repo.text;
                        //     var result = "";
                        //     switch (repo.orgType) {
                        //         case 1://1是组织架构
                        //             result += "<i class=\"fa fa-chevron-right\" aria-hidden=\"true\"></i>&nbsp;<strong>" + repo.orgName + "</strong>";
                        //             break;
                        //         case 2://2是组织部门
                        //             result += "&nbsp;&nbsp;<i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i>&nbsp;" + repo.orgName;
                        //             break;
                        //         case 3://3是部门小组
                        //             result += "&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i>&nbsp;" + repo.orgName;
                        //             break;
                        //         default:
                        //             break;
                        //     }
                        //     return result;
                        // }


                        //组织架构ztree插件
                        $.baseUtils.tree({
                            treeNodeName: "#orgTree",
                            textValue: "#orgSelect",
                            idValue: "#orgId",
                            isCheck: false,
                            ajaxUrl: "../../adminOrg/view/tree/1"
                        });

                        //隐藏组织架构下拉菜单
                        function hideMenu() {
                            $("#menuContent").fadeOut("fast");
                            $("body").unbind("mousedown", onBodyDown);
                        }

                        //显示
                        function onBodyDown(event) {
                            if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length > 0)) {
                                hideMenu();
                            }
                        }

                        //点击显示组织架构
                        $("#orgSelect").on('click', function () {
                            $("#menuContent").css({width: ($(this).width() + 24) + "px", top: $(this).outerHeight() + "px"}).slideDown("fast");
                            $("body").bind("mousedown", onBodyDown);
                        });


                        if (row != null) {
                            //角色 默认 select
                            if (row.roleId && row.roleName) {
                                roleSelect.append("<option value='" + row.roleId + "'>" + row.roleName + "</option>");
                            }

                            $('#id').val(row.id);
                            $('#nickName').val(row.nickName);
                            $('#ukey').val(row.ukey);
                            $('#userName').val(row.userName).prop("readonly", true);
                            $('#sort').val(row.sort);
                            $('#orgId').val(row.orgId);
                            $('#orgSelect').val(row.orgName);
                        } else {
                            $(".myPassword").css('display', 'block');
                            $('#password').removeAttr("readonly").removeAttr("disabled");
                            $('#confirm_password').removeAttr("readonly").removeAttr("disabled");
                        }
                    }
                });
            };
        },
        update: function () {

        }
    }
});







